<?php
/**
 * Created by PhpStorm.
 * User: lih
 * Date: 2018/4/22
 * Time: 11:02
 */

namespace frontend\api\action;

use Yii;
use yii\db\Query;
use common\models\User;

class Userlogin extends BaseAction
{

    /**
     * @param $arrayData array
     * @param $returnData array
     * @throws \Exception
     */
    public function runAction($arrayData, &$returnData)
    {
        $returnData['msg'] = '登录失败';

        if(!$this->checkRequestInput($arrayData, $returnData)) {
            throw new \Exception('input invalid');
        }

        $returnData['msg'] = '用户名或密码不正确';

        /**
         * @var $user \common\models\User
         */
        $user = User::findByUsername($arrayData['username']);
        if($user !== null
                && $user->validatePassword($arrayData['password'])) {
            if (Yii::$app->user->login($user)) {
                User::updateUserDataById(Yii::$app->user->getId(), [
                    'sessionid' => Yii::$app->session->getId(),
                ]);

                $userData = $this->getUserDataByUid(Yii::$app->user->getId());
                if(!empty($userData)) {
                    $returnData['code'] = '0';
                    $returnData['msg'] = '';
                    $returnData['sessionid'] = Yii::$app->session->getId();

                    $returnData['data'] = $userData;
                }
            }
        }

    }

    /**
     * @param $arrayData array
     * @param $returnData array
     * @return bool
     */
    private function checkRequestInput(&$arrayData, &$returnData) {
        if(empty($arrayData['username'])) {
            $returnData['msg'] = '用户名不能为空';
            return false;
        }

        if(empty($arrayData['password'])) {
            $returnData['msg'] = '密码不能为空';
            return false;
        }

        return true;
    }

}
